# -*- coding:utf-8 -*-
"""
作者:13505
日期:2021年03月16日
"""

import web
from pachong import douban
import conSql

# 渲染当前项目前端页面
ren = web.template.render('templates')

urls = (
    '/login', 'login',
    '/', 'index',
    '/index', 'index',
    '/error', 'error',
    '/manager', 'manager',
    '/registered', 'registered',
    '/success', 'success',
    '/del', 'delete',
)

app = web.application(urls, globals())


class login:

    def GET(self):
        return ren.login()

    pass

    def POST(self):
        loginUser = web.input()
        print("login-uname: " + loginUser.uname)
        print("login-pwd: " + loginUser.pwd)
        # 创建sql
        sql = "select * from userinfo where user=%s and password=%s;"
        data = (loginUser.uname, loginUser.pwd)
        num = conSql.change(sql, data)
        if num > 0:
            return ren.index(loginUser.uname)
        else:
            print('用户名或密码错误！')
            return ren.error('用户名或密码错误！')
        pass

    pass


pass


class registered:
    def GET(self):
        return ren.registered()

    pass

    def POST(self):
        regUser = web.input()
        print("reg-uname: " + regUser.uname)
        print("reg-pwd: " + regUser.pwd)
        # 查询用户名是否重复
        num = conSql.query(regUser.uname)

        if type(num) is list:
            print('用户名重复')
            return ren.error('用户名重复')
        else:
            # 将用户数据插入数据库
            result = conSql.insert((regUser.uname, regUser.pwd))
            if result > 0:
                print('注册成功！跳转登陆界面！')
                return ren.login()
            else:
                return ren.error("注册失败！")

    pass


pass


class index:

    def GET(self):
        return ren.login()

    pass

    def POST(self):
        #     对输入网址进行判断
        index_input = web.input()
        url = index_input.url

        # 测试使用，爬取豆瓣页面
        code = douban.main()
        if code == 0:
            return ren.success()
        else:
            return ren.error('爬取失败！')

    pass


pass


class error:
    def GET(self):
        return ren.error()

    pass


pass


class manager:
    def GET(self):
        # 连接数据库 查询用户信息表，并渲染至前端页面
        conn = conSql.getConn()
        cursor = conn.cursor()
        sql = "select * from userinfo"
        cursor.execute(sql)
        result = cursor.fetchall()
        conn.close()
        result = list(result)

        return ren.manager(result)

    pass

    def POST(self):
        data = web.input()
        num = conSql.query((data.oldName,))
        if num != False:
            info = (data.user, data.password, data.oldName)
            print(info)
            conSql.update(info)
        else:
            return ren.error("数据库连接失败！")
        pass

    pass


pass


class delete:
    def GET(self):
        return

    pass

    def POST(self):
        data = web.input()
        # 删除数据
        conSql.delete((data.user,))
        pass

    pass


if __name__ == '__main__':
    app.run()
